package com.example.assetmanagement.service.impl;

import com.example.assetmanagement.common.PageRequest;
import com.example.assetmanagement.common.PageResponse;
import com.example.assetmanagement.domain.User;
import com.example.assetmanagement.mapper.UserMapper;
import com.example.assetmanagement.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    private static final String DEFAULT_PASSWORD = "123456";

    @Override
    public PageResponse<User> list(PageRequest pageRequest, String username, String fullName, Integer status) {
        List<User> list = userMapper.selectPage(pageRequest.getOffset(), pageRequest.getSize(), username, fullName, status);
        long total = userMapper.count(username, fullName, status);
        return new PageResponse<>(total, list);
    }

    @Override
    public List<User> getAll() {
        return userMapper.selectAll();
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    @Transactional
    public void add(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword() != null ? user.getPassword() : DEFAULT_PASSWORD));
        userMapper.insert(user);
        if(user.getRoleIds()!=null && !user.getRoleIds().isEmpty()){
            userMapper.insertUserRoles(user.getId(), user.getRoleIds());
        }
    }

    @Override
    @Transactional
    public void update(Long id, User user) {
        user.setId(id);
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userMapper.update(user);
        if(user.getRoleIds()!=null){
            userMapper.deleteUserRoles(id);
            if(!user.getRoleIds().isEmpty())
                userMapper.insertUserRoles(id, user.getRoleIds());
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) return;
        userMapper.deleteBatch(ids);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        userMapper.updateStatus(id, status);
    }

    @Override
    @Transactional
    public void resetPassword(Long id) {
        String hashed = passwordEncoder.encode(DEFAULT_PASSWORD);
        userMapper.resetPassword(id, hashed);
    }
} 